using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading.Tasks;
using Org.BouncyCastle.Crmf;
using Publicuse.Entity;
using Publicuse.Interface;
using Publicuse.Util;

namespace Publicuse.Cache
{
  public class LoginCache
  {
    private static ConcurrentDictionary<string, UserRouteData> userRouteData = null;

    private static ConcurrentDictionary<string, string> loginUsers = null;

    private static ConcurrentDictionary<string, DateTime> onlinelist = null;
    private static List<SysLogin> sysLogins = null;

    private static ConcurrentDictionary<string, List<string>> keys = null;

    private static ConcurrentDictionary<string, DateTime> loginKey = null;

    private static ConcurrentDictionary<string, string> loginUserRoles = null;

    private static LoginCache loginCache = null;

    private static ConcurrentDictionary<string, List<UserAction>> userActions = null;

    private static ConcurrentDictionary<string, List<UserAction>> userActionList = null;

    private static ConcurrentDictionary<string, string> userPassList = null;

    private static bool isInitSystemFinsh = false;

    private static ConcurrentDictionary<string, string> loginyzm = null;

    private static ConcurrentDictionary<string, string> loginyzsuccess = null;

    private static ConcurrentDictionary<string, List<MenuSimple>> Menulist = null;

    public ConcurrentDictionary<string, string> GetLoginYzm
    {
      get { return loginyzm; }
    }

    public ConcurrentDictionary<string, string> GetLoginYzmSuccess
    {
      get { return loginyzsuccess; }
    }

    private static int SysTimeOut { get; set; }

    public static bool GetisInitSystemFinsh
    {
      get { return isInitSystemFinsh; }
    }

    private static ConcurrentDictionary<string, List<Menu>> loginmenulist = null;

    private LoginCache() { }

    static LoginCache()
    {
      userRouteData = new ConcurrentDictionary<string, UserRouteData>();
      loginUsers = new ConcurrentDictionary<string, string>();
      onlinelist = new ConcurrentDictionary<string, DateTime>();
      userPassList = new ConcurrentDictionary<string, string>();
      loginCache = new LoginCache();
      sysLogins = new List<SysLogin>();
      keys = new ConcurrentDictionary<string, List<string>>();
      loginKey = new ConcurrentDictionary<string, DateTime>();
      loginUserRoles = new ConcurrentDictionary<string, string>();
      userActions = new ConcurrentDictionary<string, List<UserAction>>();
      userActionList = new ConcurrentDictionary<string, List<UserAction>>();
      loginyzm = new ConcurrentDictionary<string, string>();
      loginyzsuccess = new ConcurrentDictionary<string, string>();
      Menulist = new ConcurrentDictionary<string, List<MenuSimple>>();
      isInitSystemFinsh = true;
      loginmenulist = new ConcurrentDictionary<string, List<Menu>>();
    }

    public void AddUserRouteData(string token, UserRouteData routeData)
    {
      if (!userRouteData.ContainsKey(token))
      {
        userRouteData.TryAdd(token, routeData);
      }
    }

    public void RemoveUserRouteData(string token)
    {
      if (userRouteData.ContainsKey(token))
      {
        userRouteData.Remove(token, out var list);
      }
    }

    public UserRouteData GetUserRouteData(string token)
    {
      UserRouteData routeData = new UserRouteData();
      if (userRouteData.ContainsKey(token))
      {
        userRouteData.TryGetValue(token, out routeData);
      }
      return routeData;
    }

    public void AddLoginMenuList(string token, List<Menu> menulist)
    {
      if (!loginmenulist.ContainsKey(token))
      {
        loginmenulist.TryAdd(token, menulist);
      }
    }

    public void RemoveLoginMenuList(string token, List<Menu> menulist)
    {
      if (loginmenulist.ContainsKey(token))
      {
        loginmenulist.Remove(token, out var list);
      }
    }

    public List<Menu> GetLoginMenu(string token)
    {
      List<Menu> list = new List<Menu>();
      if (loginmenulist.ContainsKey(token))
      {
        loginmenulist.TryGetValue(token, out list);
      }
      return list;
    }

    public void AddLoginUser(string ucode)
    {
      if (!loginUsers.ContainsKey(ucode))
      {
        loginUsers.TryAdd(ucode, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
      }
    }

    public bool haveLogin(string ucode)
    {
      if (loginUsers.ContainsKey(ucode))
      {
        if (string.IsNullOrEmpty(GetUserLoginTime(ucode)))
        {
          return false;
        }
        else
        {
          return true;
        }
      }
      else
      {
        return false;
      }
    }

    /// <summary>
    /// 添加登陆用户用户名、角色名、密码
    /// </summary>
    /// <param name="token"></param>
    /// <param name="rName"></param>
    /// <param name="rIds"></param>
    /// <param name="uId"></param>
    /// <param name="uPwd"></param>
    /// <param name="baseService"></param>
    public void SaveLoginInfo(
      string token,
      string rName,
      string rIds,
      long uId,
      string uPwd,
      IMySqlSugarService baseService
    )
    {
      var tableName = TableAtributeUtil.GetTable<Spconf>();
      loginKey.TryAdd(token, DateTime.Now);
      loginUserRoles.TryAdd(token, uId + "-" + rIds);
      var sql = $"select sValue from {tableName} where sCode='SysTimeOut' ";
      var msg = string.Empty;
      var dt = baseService.GetDataTable(sql, null, out msg);
      if (dt.Rows.Count > 0)
      {
        try
        {
          SysTimeOut = Convert.ToInt32(dt.Rows[0]["sValue"].ToString());
        }
        catch (Exception e)
        {
          SysTimeOut = 180;
        }
      }
    }

    public void RemoveLoginUser(string ucode)
    {
      if (loginUsers.ContainsKey(ucode))
      {
        loginUsers.TryRemove(ucode, out var ltime);
      }
    }

    public static LoginCache GetLoginCache
    {
      get { return loginCache; }
    }

    public void GetUserRole(string token, out string value)
    {
      loginUserRoles.TryGetValue(token, out value);
    }

    /// <summary>
    /// 保存系统用户在线信息
    /// </summary>
    /// <param name="ip"></param>
    /// <param name="name"></param>
    /// <param name="time"></param>
    /// <param name="token"></param>
    public void AddsysLogins(string ip, string name, DateTime time, string token)
    {
      SysLogin sys = new SysLogin()
      {
        ip = ip,
        name = name,
        time = time,
        token = token
      };
      if (sysLogins.Count > 0)
      {
        //相同的IP不添加，可能是不同的浏览器
        var havedata = sysLogins.Where(o => o.ip == ip).ToList();
        if (havedata.Count == 0)
        {
          sysLogins.Add(sys);
        }
        else
        {
          sysLogins.Add(sys);
        }
      }
      else
      {
        sysLogins.Add(sys);
      }
    }

    public void AddUserRole(string tokenkey, long uId, IMySqlSugarService mySqlSugar)
    {
      var sql = $"select rids from {TableAtributeUtil.GetTable<UserRole>()} where uId={uId};";
      var data = mySqlSugar.GetDataTable(sql, null, out var msg);
      if (string.IsNullOrEmpty(msg) && data != null)
      {
        var rids = data.Rows[0]["rids"].ToString();
        if (!loginUserRoles.ContainsKey(tokenkey))
        {
          loginUserRoles.TryAdd(tokenkey, rids);
        }
      }
    }

    /// <summary>
    /// 获取所有在线用户
    /// </summary>
    /// <returns></returns>
    public List<string> GetAllOnline()
    {
      return onlinelist.Keys.ToList();
    }

    /// <summary>
    /// 获取用户在线时间
    /// </summary>
    /// <param name="token"></param>
    /// <returns></returns>
    public string GetOnlineTime(string token)
    {
      var time = string.Empty;
      if (onlinelist.ContainsKey(token))
      {
        onlinelist.TryGetValue(token, out var timevalue);
        var sjc = DateTime.Now - timevalue;
        if (sjc.Minutes < 2)
        {
          return timevalue.ToString("yyyy-MM-dd HH:mm:ss");
        }
        else
        {
          onlinelist.Remove(token, out var timevaueb);
          HttpContextExtendBase.RemoveToken(token);
        }
      }
      return time;
    }

    /// <summary>
    /// 获取用户是否已经登录，如果活动时间超过2分钟则视为退出系统没有登录
    /// </summary>
    /// <param name="ucode"></param>
    /// <returns></returns>
    public string GetUserLoginTime(string ucode)
    {
      var time = string.Empty;
      if (loginUsers.ContainsKey(ucode))
      {
        loginUsers.TryGetValue(ucode, out var timevalue);
        var sjc = DateTime.Now - Convert.ToDateTime(timevalue);
        if (sjc.Minutes < 2)
        {
          return timevalue;
        }
        else
        {
          loginCache.RemoveLoginUser(ucode);
        }
      }
      return time;
    }

    /// <summary>
    /// 重设用户在线时间
    /// </summary>
    /// <param name="token"></param>
    /// <returns></returns>
    public void SetOnlineTime(string token)
    {
      if (onlinelist.ContainsKey(token))
      {
        onlinelist.Remove(token, out var timevalue);
        onlinelist.TryAdd(token, DateTime.Now);
      }
    }

    /// <summary>
    /// 重设用户在线时间
    /// </summary>
    /// <param name="ucode"></param>
    /// <returns></returns>
    public void SetUserLoginTime(string ucode)
    {
      if (loginUsers.ContainsKey(ucode))
      {
        loginUsers.Remove(ucode, out var timevalue);
        loginUsers.TryAdd(ucode, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
      }
    }

    /// <summary>
    /// 退回登录清除用户的权限信息
    /// </summary>
    /// <param name="mySqlSugar"></param>
    /// <param name="userCode"></param>
    public void LoginOut(IMySqlSugarService mySqlSugar, string userCode)
    {
      string msg = string.Empty;
      var ucode = HttpContextExtendBase.GetLoginCode();
      loginUsers.Remove(ucode, out var timeb);
      var jwttoken = HttpContextExtendBase.Current.Request.Headers["token"].ToString();
      var appid = HttpContextExtendBase.Current.Request.Headers["appid"].ToString();
      if (
        !string.IsNullOrEmpty(jwttoken)
        && jwttoken != null
        && string.Compare(jwttoken, "null", true) != 0
      )
      {
        HttpContextExtendBase.RemoveToken(jwttoken);
        onlinelist.TryRemove(jwttoken, out var timevalue);
        DateTime time = default(DateTime);
        loginKey.TryRemove(jwttoken, out time);
        var tableName = TableAtributeUtil.GetTable<SigninInfo>();
        RemovesysLogins(jwttoken);
        var userqx = string.Empty;
        userPassList.TryRemove(jwttoken, out userqx);
        var sql = $"select cTime from {tableName} where loginid='{jwttoken}'";
        var data = mySqlSugar.Query<SigninInfo>(sql, out msg);
        if (data != null && data.Count() > 0)
        {
          var logintime = Convert.ToDateTime(data.FirstOrDefault().cTime);
          var sjc = DateTime.Now - logintime;
          var onlinetime = $"{sjc.Hours}小时{sjc.Minutes}分钟{sjc.Seconds}秒 ";
          sql =
            $"update {tableName} set loginouttime='{DateTime.Now}',onlinetime='{onlinetime}' where loginid='{jwttoken}';";
          mySqlSugar.ExecuteSql(sql, out msg, null);

          var headers = HttpContextExtendBase.Current.Request.Headers;
          if (headers.ContainsKey("X-Forwarded-For"))
          {
            HttpContextExtendBase.Current.Connection.RemoteIpAddress = IPAddress.Parse(
              headers["X-Forwarded-For"]
                .ToString()
                .Split(',', StringSplitOptions.RemoveEmptyEntries)[0]
            );
          }
          if (headers.ContainsKey("X-Forwarded-For"))
          {
            HttpContextExtendBase.Current.Connection.RemoteIpAddress = IPAddress.Parse(
              headers["X-Forwarded-For"]
                .ToString()
                .Split(',', StringSplitOptions.RemoveEmptyEntries)[0]
            );
          }
          var remoteIp =
            LogClass.GetIPAddress()
            + "|"
            + headers["X-Real-IP"].ToString()
            + "|"
            + headers["X-Forwarded-For"].ToString();
          if (string.Compare(remoteIp, "::1", true) == 0)
          {
            remoteIp = HttpContextExtendBase
              .Current.Connection.LocalIpAddress.MapToIPv4()
              ?.ToString();
          }
          if (remoteIp.Split(':').Length >= 3)
          {
            remoteIp = remoteIp.Split(':')[3];
          }
          if (!string.IsNullOrEmpty(remoteIp))
          {
            remoteIp = remoteIp.Replace("unknow", "").Replace("|", "");
          }
          var RemoteIpAddress = HttpContextExtendBase.Current.Connection.RemoteIpAddress;
          var ipaddress = string.Empty;
          var newripad = RemoteIpAddress.ToString();
          if (!string.IsNullOrEmpty(newripad))
          {
            if (string.Compare(newripad, "::1", true) != 0)
            {
              ipaddress = $"{remoteIp + "|" + RemoteIpAddress}";
            }
            else
            {
              ipaddress = remoteIp;
            }
          }
          else
          {
            ipaddress = remoteIp;
          }
          ipaddress = ipaddress.Replace("|::ffff:", "");

          var lrole = HttpContextExtendBase.GetLoginrName();
          Log log = new Log()
          {
            lmodule = "用户管理",
            ltype = "用户退出系统",
            luser = ucode,
            lrole = lrole,
            lcontent = "用户退出系统成功",
            lsuccess = 1,
            status = 1,
            createuser = ucode,
            modifyuser = ucode,
            ipaddress = ipaddress,
          };
          mySqlSugar.InserBackId<Log>(log, out msg);
        }
        userActions.TryRemove(jwttoken, out var list);
        userActionList.TryRemove(jwttoken, out var listb);
        userRouteData.TryRemove(jwttoken, out var listc);
      }
    }

    public void AddJwtToken(string token, IMySqlSugarService mySqlSugar)
    {
      onlinelist.TryAdd(token, DateTime.Now);
      var info = JwtUtil.GetJwtDecode(token);
      var UserAgent = HttpContextExtendBase.Current.Request.Headers["User-Agent"].ToString();
      var headers = HttpContextExtendBase.Current.Request.Headers;
      if (headers.ContainsKey("X-Forwarded-For"))
      {
        HttpContextExtendBase.Current.Connection.RemoteIpAddress = IPAddress.Parse(
          headers["X-Forwarded-For"].ToString().Split(',', StringSplitOptions.RemoveEmptyEntries)[0]
        );
      }
      if (headers.ContainsKey("X-Forwarded-For"))
      {
        HttpContextExtendBase.Current.Connection.RemoteIpAddress = IPAddress.Parse(
          headers["X-Forwarded-For"].ToString().Split(',', StringSplitOptions.RemoveEmptyEntries)[0]
        );
      }
      var remoteIp =
        LogClass.GetIPAddress()
        + "|"
        + headers["X-Real-IP"].ToString()
        + "|"
        + headers["X-Forwarded-For"].ToString();
      if (string.Compare(remoteIp, "::1", true) == 0)
      {
        remoteIp = HttpContextExtendBase.Current.Connection.LocalIpAddress.MapToIPv4()?.ToString();
      }
      if (remoteIp.Split(':').Length >= 3)
      {
        remoteIp = remoteIp.Split(':')[3];
      }
      if (!string.IsNullOrEmpty(remoteIp))
      {
        remoteIp = remoteIp.Replace("unknow", "").Replace("|", "");
      }
      var RemoteIpAddress = HttpContextExtendBase.Current.Connection.RemoteIpAddress;
      var ipaddress = string.Empty;
      var newripad = RemoteIpAddress.ToString();
      if (!string.IsNullOrEmpty(newripad))
      {
        if (string.Compare(newripad, "::1", true) != 0)
        {
          ipaddress = $"{remoteIp + "|" + RemoteIpAddress}";
        }
        else
        {
          ipaddress = remoteIp;
        }
      }
      else
      {
        ipaddress = remoteIp;
      }
      ipaddress = ipaddress.Replace("|::ffff:", "");
      var nowtime = DateTime.Now;
      SigninInfo signinInfo = new SigninInfo()
      {
        loginUserCode = info.uCode,
        uId = info.Id.GetIntValue(),
        cTime = nowtime,
        uTime = nowtime,
        logincode = info.uCode,
        loginid = token,
        browser = UserAgent,
        osystem = LogClass.GetSystemType(),
        osystemtype = LogClass.GetSystemName(),
        ipaddress = ipaddress,
        ipv4address = ipaddress,
        lmacaddress = LogClass.GetMacAddress(),
      };
      mySqlSugar.InserBackId(signinInfo, out var msg);
      HttpContextExtendBase.AddJwtToken(token, info);
    }

    public void GetJwtToken(string token, out JwtToken jwtToken)
    {
      HttpContextExtendBase.GetJwtToken(token, out jwtToken);
    }

    public void AddUserPass(string name, string pwd)
    {
      if (!userPassList.ContainsKey(name))
        userPassList.TryAdd(name, pwd);
    }

    public void AddMenu(string key, List<MenuSimple> value)
    {
      if (!Menulist.ContainsKey(key))
      {
        Menulist.TryAdd(key, value);
      }
    }

    public void ClearMenu()
    {
      Menulist.Clear();
    }

    public List<MenuSimple> GetMenuName(string key)
    {
      List<MenuSimple> name = new List<MenuSimple>();
      Menulist.TryGetValue(key, out name);
      return name;
    }

    public List<MenuSimple> GetMenuAll()
    {
      return Menulist.Values.FirstOrDefault();
    }

    /// <summary>
    /// 保存用户请求登录验证码信息
    /// </summary>
    /// <param name="time"></param>
    /// <param name="yzm"></param>
    public void AddUserLoginYzmSuccess(string time, string yzm)
    {
      if (!loginyzsuccess.ContainsKey(time))
        loginyzsuccess.TryAdd(time, yzm);
    }

    /// <summary>
    /// 保存用户请求登录验证码信息
    /// </summary>
    /// <param name="time"></param>
    /// <param name="yzm"></param>
    public void AddUserLoginYzm(string time, string yzm)
    {
      if (!loginyzm.ContainsKey(time))
        loginyzm.TryAdd(time, yzm);
    }

    /// <summary>
    /// 移除用户请求登录验证码信息
    /// </summary>
    /// <param name="time"></param>
    public void RemoveUserLoginYzm(string time)
    {
      loginyzm.TryRemove(time, out var msg);
      var gg = msg;
    }

    /// <summary>
    /// 移除用户请求登录正确验证码信息
    /// </summary>
    /// <param name="time"></param>
    public void RemoveUserLoginYzmSuccess(string time)
    {
      loginyzsuccess.TryRemove(time, out var msg);
      var gg = msg;
    }

    public string GetUserPwd(string name)
    {
      var pwd = string.Empty;

      userPassList.TryGetValue(name, out pwd);
      return pwd;
    }

    public List<SysLogin> GSysLogins()
    {
      List<SysLogin> list = new List<SysLogin>();
      foreach (var item in sysLogins)
      {
        var sjc = DateTime.Now - item.time;
        item.sjd = $"{sjc.Hours}小时{sjc.Minutes}分钟{sjc.Seconds}秒";
        list.Add(item);
      }
      return list;
    }

    /// <summary>
    /// 移除系统用户在线信息
    /// </summary>
    /// <param name="token"></param>
    public void RemovesysLogins(string token)
    {
      var logintoken = sysLogins.Where(o => o.token == token).ToList();
      if (logintoken.Count > 0)
      {
        sysLogins.Remove(logintoken.FirstOrDefault());
      }
    }

    /// <summary>
    /// 获取系统登录超时时间
    /// </summary>
    /// <param name="mySqlSugar"></param>
    /// <param name="token"></param>
    public void GetLoginTimeout(IMySqlSugarService mySqlSugar, string token)
    {
      loginKey.TryAdd(token, DateTime.Now);
      var tableName = TableAtributeUtil.GetTable<Spconf>();
      var sql = $"select sValue from {tableName} where sCode='SysTimeOut' ";
      var msg = string.Empty;
      var data = mySqlSugar.Query<Spconf>(sql, out msg);
      if (data.Count() > 0)
      {
        try
        {
          SysTimeOut = Convert.ToInt32(data.FirstOrDefault().sValue);
        }
        catch (Exception e)
        {
          SysTimeOut = 180;
        }
      }
    }

    /// <summary>
    /// 添加登陆用户按钮操作权限信息
    /// </summary>
    /// <param name="token"></param>
    /// <param name="uActions"></param>
    public void SaveLoginAction(string token, List<UserAction> uActions)
    {
      if (userActions.Count > 0)
      {
        if (userActions.ContainsKey(token))
        {
          Task.Factory.StartNew(() =>
            {
              var list = new List<UserAction>();
              userActions.TryRemove(token, out list);
            })
            .ContinueWith(res =>
            {
              userActions.TryAdd(token, uActions);
            });
        }
        else
        {
          userActions.TryAdd(token, uActions);
        }
      }
      else
      {
        userActions.TryAdd(token, uActions);
      }

      isInitSystemFinsh = true;
    }

    public List<UserAction> GetLoginAction(string token)
    {
      List<UserAction> uActions = new List<UserAction>();
      if (!string.IsNullOrEmpty(token))
      {
        userActionList.TryGetValue(token, out uActions);
      }
      return uActions;
    }

    /// <summary>
    /// 添加登陆用户按钮操作权限信息
    /// </summary>
    /// <param name="token"></param>
    /// <param name="uActions"></param>
    public void SaveLoginActionList(string token, List<UserAction> uActions)
    {
      if (userActionList.Count > 0)
      {
        if (userActionList.ContainsKey(token))
        {
          Task.Factory.StartNew(() =>
            {
              var list = new List<UserAction>();
              userActionList.TryRemove(token, out list);
            })
            .ContinueWith(res =>
            {
              userActionList.TryAdd(token, uActions);
            });
        }
        else
        {
          userActionList.TryAdd(token, uActions);
        }
      }
      else
      {
        userActionList.TryAdd(token, uActions);
      }

      isInitSystemFinsh = true;
    }

    private static object lockhave = new object();

    /// <summary>
    /// 判断当前用户是否有执行按钮的操作权限
    /// </summary>
    /// <param name="tokenkey"></param>
    /// <param name="token"></param>
    /// <param name="url"></param>
    /// <returns></returns>
    public bool isHaveAction(string tokenkey, JwtToken token, string url)
    {
      if (string.Compare(url, "api/User/CheckLoginTimeOut", true) == 0)
      {
        return true;
      }
      List<UserAction> user = new List<UserAction>();
      userActions.TryGetValue(tokenkey, out user);
      if (user == null || user.Count == 0)
      {
        return false;
      }
      else
      {
        if (
          string.Compare(token.uCode, "ajng", true) == 0
          || string.Compare(token.uCode, "sysadmin", true) == 0
        )
          return true;

        return user.Any(o => o.url.ToLower() == url.ToLower());
      }
    }

    /// <summary>
    /// 判断当前用户是否有操作权限
    /// </summary>
    /// <param name="ucode"></param>
    /// <param name="api"></param>
    /// <returns></returns>
    public bool HaveMenu(string ucode, string api)
    {
      var LoginrName = HttpContextExtendBase.GetLoginrName();
      if (
        !string.IsNullOrEmpty(ucode)
        && string.Compare(api.ToLower(), "/api/Menu/Login".ToLower(), true) != 0
      )
      {
        if (
          LoginrName.Split(',').Any(o => o == "超级管理员")
          || string.Compare("超级管理员", LoginrName, true) == 0
          || string.Compare("ajng", ucode, true) == 0
        )
        {
          return true;
        }
        else
        {
          api = api.TrimStart('/');
          var token = HttpContextExtendBase.GetTokenStr();
          List<UserAction> user = new List<UserAction>();
          userActionList.TryGetValue(token, out user);
          if (user != null && user.Count > 0)
          {
            var typeapi = api.Split('/');
            switch (typeapi[2])
            {
              case "GetSysModuleList":
                api = api.Replace("GetSysModuleList", "CheckGetList");
                break;
              case "GetList":
                api = api.Replace("GetList", "CheckGetList");
                break;
              case "GetLista":
                api = api.Replace("GetLista", "CheckGetList");
                break;
              case "GetListb":
                api = api.Replace("GetListb", "CheckGetList");
                break;
              case "GetListc":
                api = api.Replace("GetListc", "CheckGetList");
                break;
              case "GetListd":
                api = api.Replace("GetListd", "CheckGetList");
                break;
              case "GetListe":
                api = api.Replace("GetListe", "CheckGetList");
                break;
              case "GetListf":
                api = api.Replace("GetListf", "CheckGetList");
                break;
              case "GetListg":
                api = api.Replace("GetListg", "CheckGetList");
                break;
              case "GetListh":
                api = api.Replace("GetListh", "CheckGetList");
                break;
              case "GetData":
                api = api.Replace("GetData", "CheckGetList");
                break;
              case "GetTreeList":
                api = api.Replace("GetTreeList", "CheckGetList");
                break;
              case "GetSendInfo":
                api = api.Replace("GetData", "CheckGetList");
                break;
              case "SaveSendInfo":
                api = api.Replace("GetData", "CheckGetList");
                break;
              case "GetUserLoginInfo":
                api = api.Replace("GetUserLoginInfo", "CheckGetList");
                break;
              case "GetListAll":
                api = api.Replace("GetListAll", "CheckGetList");
                break;
              case "GetStatistics":
                api = api.Replace("GetStatistics", "CheckGetList");
                break;
              case "AddResourceToUser":
                api = api.Replace("AddResourceToUser", "CheckAdd");
                break;
              case "AddRoleToUser":
                api = api.Replace("AddRoleToUser", "CheckAdd");
                break;
              case "SaveUserCompany":
                api = api.Replace("SaveUserCompany", "CheckAdd");
                break;
              case "AddOrUpdate":
                api = api.Replace("AddOrUpdate", "CheckAdd");
                break;
              case "UpdatePwd":
                api = api.Replace("UpdatePwd", "CheckAdd");
                break;
              case "Delete":
                api = api.Replace("Delete", "CheckDelete");
                break;
              case "DeleteFile":
                api = api.Replace("DeleteFile", "CheckDelete");
                break;
              case "Reduction":
                api = api.Replace("Reduction", "CheckDelete");
                break;
              case "ImportExcel":
                api = api.Replace("ImportExcel", "CheckImport");
                break;
              case "UploadFile":
                api = api.Replace("UploadFile", "CheckImport");
                break;
              case "ExportData":
                api = api.Replace("ExportData", "CheckExport");
                break;
              case "ExportDataa":
                api = api.Replace("ExportDataa", "CheckExport");
                break;
              case "ExportDatab":
                api = api.Replace("ExportDatab", "CheckExport");
                break;
              case "ExportDatac":
                api = api.Replace("ExportDatac", "CheckExport");
                break;
              case "ExportDatad":
                api = api.Replace("ExportDatad", "CheckExport");
                break;
              case "ExportDatae":
                api = api.Replace("ExportDatae", "CheckExport");
                break;
              case "ExportDataf":
                api = api.Replace("ExportDataf", "CheckExport");
                break;
              case "ExportDatag":
                api = api.Replace("ExportDatag", "CheckExport");
                break;
              case "ExportDatah":
                api = api.Replace("ExportDatah", "CheckExport");
                break;
              case "ExportDatai":
                api = api.Replace("ExportDatai", "CheckExport");
                break;
              case "ExportDataj":
                api = api.Replace("ExportDataj", "CheckExport");
                break;
              case "ExportDatak":
                api = api.Replace("ExportDatak", "CheckExport");
                break;
              case "ExportDatal":
                api = api.Replace("ExportDatal", "CheckExport");
                break;
              case "ExportDatam":
                api = api.Replace("ExportDatam", "CheckExport");
                break;
              case "ExportDatan":
                api = api.Replace("ExportDatan", "CheckExport");
                break;
              case "Confirm":
                api = api.Replace("Confirm", "CheckAudit");
                break;
              case "ConfirmAll":
                api = api.Replace("ConfirmAll", "CheckAudit");
                break;
              case "Upload":
                api = api.Replace("Upload", "CheckUpload");
                break;
              case "Down":
                api = api.Replace("Upload", "CheckDown");
                break;
            }

            user.ForEach(item =>
            {
              item.url = item.url.ToLower().Replace("loginlog", "log");
              item.url = item.url.ToLower().Replace("controllerlog", "log");
              item.url = item.url.ToLower().Replace("operatelog", "log");
            });
            var haveqx = user.Any(o => o.url.ToLower() == api.ToLower());
            if (string.Compare(typeapi[2], "AddOrUpdate", true) == 0 && !haveqx)
            {
              api = api.Replace("CheckAdd", "CheckUpdate");
              haveqx = user.Any(o => o.url.ToLower() == api.ToLower());
            }
            if (string.Compare(typeapi[2], "CheckAdd", true) == 0 && !haveqx)
            {
              api = api.Replace("CheckAdd", "CheckAU");
              haveqx = user.Any(o => o.url.ToLower() == api.ToLower());
            }
            return haveqx;
          }
          else
          {
            return true;
          }
        }
      }
      else
      {
        return true;
      }
    }

    /// <summary>
    /// 判断用户是否在线
    /// </summary>
    /// <param name="token"></param>
    /// <returns></returns>
    public bool isonline(string token)
    {
      var ischeck = false;
      return ischeck;
    }

    /// <summary>
    /// 判断会话时间是否已经超时
    /// </summary>
    /// <param name="jwttoken"></param>
    /// <param name="token"></param>
    /// <returns></returns>
    public bool isTimeout(string jwttoken, JwtToken token)
    {
      if (token != null)
      {
        var logintime = Convert.ToDateTime(token.cTime);
        var SysTimeOutb = token.SysTimeOut.GetIntValue();
        var sjc = DateTime.Now - logintime;
        var timeout = SysTimeOutb / 60;
        if (sjc.Hours >= timeout || sjc.Days > 0)
        {
          return true;
        }
        else
        {
          token.cTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
          HttpContextExtendBase.RemoveToken(jwttoken);
          HttpContextExtendBase.AddJwtToken(jwttoken, token);
          return false;
        }
      }
      else
      {
        return true;
      }
    }

    /// <summary>
    /// 清除所有缓存数据
    /// </summary>
    public void ClearSeesion()
    {
      isInitSystemFinsh = false;
      keys.Clear();
      loginKey.Clear();
      userPassList.Clear();
      onlinelist.Clear();
      HttpContextExtendBase.ClearToken();
    }

    /// <summary>
    /// 用户解锁
    /// </summary>
    /// <param name="loginToken"></param>
    /// <param name="pwd"></param>
    /// <returns></returns>
    public bool GetLockscreen(string loginToken, string pwd)
    {
      var curpwd = string.Empty;
      userPassList.TryGetValue(loginToken, out curpwd);
      if (string.Compare(curpwd, EnDecryptionUtil.DESEncryption(pwd), true) == 0)
        return true;
      else
        return false;
    }
  }

  /// <summary>
  /// 系统在线用户信息
  /// </summary>
  public class SysLogin
  {
    /// <summary>
    /// 登录用户token
    /// </summary>
    public string token { get; set; }

    /// <summary>
    /// 登录IP
    /// </summary>
    public string ip { get; set; }

    /// <summary>
    /// 登录用户
    /// </summary>
    public string name { get; set; }

    /// <summary>
    /// 登录时间
    /// </summary>
    public DateTime time { get; set; }

    /// <summary>
    /// 用户在线时间
    /// </summary>
    public string sjd { get; set; }
  }

  public class LogClass
  {
    public string ModuleName { get; set; }

    public string ModuleAction { get; set; }

    public string SpadminName { get; set; }

    public string IpAddress { get; set; }

    public DateTime CreateTime { get; set; }

    public int IsPassSuccess { get; set; }

    public string SystemRemark { get; set; }

    public string Exception { get; set; }

    public LogClass()
    {
      this.CreateTime = DateTime.Now;
      this.IpAddress = GetIPAddress() + "|" + GetClientLocalIPv4Address();
      this.SystemRemark = GetSystemName() + "|" + GetSystemType();
      this.IsPassSuccess = 0;
    }

    public static string GetIPAddress()
    {
      try
      {
        //获取IP地址
        string st = "";
        ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
        ManagementObjectCollection moc = mc.GetInstances();
        foreach (ManagementObject mo in moc)
        {
          if ((bool)mo["IPEnabled"] == true)
          {
            //st=mo["IpAddress"].ToString();
            System.Array ar;
            ar = (System.Array)(mo.Properties["IpAddress"].Value);
            st = ar.GetValue(0).ToString();
            break;
          }
        }
        moc = null;
        mc = null;
        return st;
      }
      catch
      {
        return "unknow";
      }
      finally { }
    }

    /// <summary>
    /// 获取本机MAC地址
    /// </summary>
    /// <returns>本机MAC地址</returns>
    public static string GetMacAddress()
    {
      string strMac = string.Empty;
      try
      {
        ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
        ManagementObjectCollection moc = mc.GetInstances();
        foreach (ManagementObject mo in moc)
        {
          if ((bool)mo["IPEnabled"] == true)
          {
            try
            {
              strMac = mo["MacAddress"].ToString();
            }
            catch (Exception ea) { }
          }
        }
        moc = null;
        mc = null;
        return strMac;
      }
      catch (Exception eb) { }
      if (string.IsNullOrEmpty(strMac))
      {
        foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
        {
          if (
            nic.NetworkInterfaceType != NetworkInterfaceType.Loopback
            && nic.OperationalStatus == OperationalStatus.Up
            && nic.Name == "以太网"
          )
          {
            strMac = nic.GetPhysicalAddress().ToString();
          }
        }
      }
      return strMac;
    }

    /// <summary>
    /// 获取操作系统类型
    /// </summary>
    /// <returns>操作系统类型</returns>
    public static string GetSystemType()
    {
      try
      {
        string strSystemType = string.Empty;
        ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
        ManagementObjectCollection moc = mc.GetInstances();
        foreach (ManagementObject mo in moc)
        {
          strSystemType = mo["SystemType"].ToString();
        }
        moc = null;
        mc = null;
        return strSystemType;
      }
      catch
      {
        return "unknown";
      }
    }

    /// <summary>
    /// 获取操作系统名称
    /// </summary>
    /// <returns>操作系统名称</returns>
    public static string GetSystemName()
    {
      try
      {
        string strSystemName = string.Empty;
        ManagementObjectSearcher mos = new ManagementObjectSearcher(
          "root\\CIMV2",
          "SELECT PartComponent FROM Win32_SystemOperatingSystem"
        );
        foreach (ManagementObject mo in mos.Get())
        {
          strSystemName = mo["PartComponent"].ToString();
        }
        mos = new ManagementObjectSearcher(
          "root\\CIMV2",
          "SELECT Caption FROM Win32_OperatingSystem"
        );
        foreach (ManagementObject mo in mos.Get())
        {
          strSystemName = mo["Caption"].ToString();
        }
        return strSystemName;
      }
      catch
      {
        return "unknown";
      }
    }

    /// <summary>
    /// 获取客户端内网IPv4地址
    /// </summary>
    /// <returns>客户端内网IPv4地址</returns>
    public static string GetClientLocalIPv4Address()
    {
      string strLocalIP = string.Empty;
      try
      {
        IPHostEntry ipHost = Dns.Resolve(Dns.GetHostName());
        IPAddress ipAddress = ipHost.AddressList[0];
        strLocalIP = ipAddress.ToString();
        return strLocalIP;
      }
      catch
      {
        return "unknown";
      }
    }
  }
}
